<template>
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    @load="onLoad"
  >
    <CommentItem
      v-for="(item, index) in list"
      :key="index"
      :comment="item"
      @reply-click="$emit('reply-click', $event)"
      @updateCount="
        item.like_count = $event.count
        item.is_liking = $event.is_liking
      "
    />
  </van-list>
</template>
<script>
import { getComments } from '@/api/comment'
import CommentItem from './comment-item'
export default {
  name: 'CommentList',
  props: {
    articleId: {
      type: [Number, String, Object],
      required: true
    },
    list: {
      type: Array,
      required: true
    }
  },
  components: {
    CommentItem
  },
  data () {
    return {
      articleList: this.list, // 评论列表
      loading: false, // 上拉加载更多的 loading
      finished: false, // 是否加载结束
      offset: null, // 获取下一页数据的标记
      limit: 10
    }
  },
  created () {
    this.onLoad()
  },
  methods: {
    async onLoad () {
      try {
        const res = await getComments({
          type: 'a', // 评论类型，a-对文章(article)的评论，c-对评论(comment)的回复
          source: this.articleId.toString(),
          offset: this.offset,
          limit: this.limit
        })
        console.log(res)
        this.articleList.push(...res.data.results)
        // 3. 将 loading 设置为 false
        // 把文章评论的总数量传递到外部
        this.$emit('onloadSuccess', res.data.total_count)
        this.loading = false
        if (res.data.results.length) {
          this.offset = res.data.last_id
        } else {
          this.finished = true
        }
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
